LuisPinto LuisPinto - 1 year ago 59
Node.js Question

How to wait between promises

I have a command that returns before fulfilling, so I want to wait a little bit before following the promise chain. Is there any best practice to do so?

new Promise(function (resolve, reject) {
exec('netbeast new test-app', function (err, stdout, stderr) {
if (err) return reject(err)
else return resolve(PATH_TO_APP)
.then(fs.readFileAsync.bind(fs, PATH_TO_APP + '/server.js'))
.then(function (data) {
var shebang = data.toString().slice(0, data.toString().indexOf('\n'))
shebang.should.equal('#!/usr/bin/env node')
return Promise.resolve()
.then(fs.readJsonAsync.bind(fs, PATH_TO_APP + '/package.json'))
.then(function (data) {
return fs.accessAsync(PATH_TO_APP + '/' + data.main, fs.X_OK)

Answer Source

It probably can be useful in some use cases where it is convenient to wait a little bit before starting another action. I think the simplest way would be:

.then(function() {
    return new Promise(function (resolve, reject) {
         setTimeout(resolve, TIME_TO_WAIT_IN_ms)

EDIT: I do not think there is a "best practice" for this. Waiting, as commented above, is not contemplated in async programming. However I imagine it can be used in edge cases where, as asked, a workaround is needed.