I want to bind promises sequentially, inside a loop. I need this to user accounts, where the result of one operation depends on another. I am trying to write a flat version - all code in one place, using bind. That's at least what I wanted. I wrapped promises around two create methods, as below:
function create(myApi, record) { return new Promise(function (resolve, reject) { myApi.create(record, function (err, result) { if (err) reject(err); else resolve(result); }); }); } function createUser(myApi, record) { return new Promise(function (resolve, reject) { myApi.createUser(record, function (err, result) { if (err) reject(err); else resolve(result); }); }); } Now, I want to create users in a loop as:
for ( var i = 0; i < dummyData.accounts.length; i++) { var cursorUser = dummyData.accounts[i]; var auth0User = { email: cursorUser.email, password: cursorUser.password, connection: 'Username-Password-Authentication' }; createUser(api, auth0User) .then( function(auth0Info) { console.log("Auth0 userInfo: ", auth0Info); cursorUser.authProfile = auth0Info; create(accountsAPIService, cursorUser) .then(function (account) { console.log("created account:", account); }) .catch(function (err) { console.log('count not create account for user, error: ', err, '\nfor: ', auth0User); }); }) .catch(function (err) { console.log('could not create auth0 user, error: ', err, '\nfor: ', auth0User); }); } Since the two method are asynchronous, it is of course not working correctly. Calls are not executed sequentially. I want to chain promises so that create does not run until a call from createUser returned. Tried using bind, but it did not work for me. It is how one should do the sequential chaining? I bind on .then of the createUser? Please advise.