JavaScript Promises and setTimeout

二次信任 提交于 2019-12-03 09:03:55

You need to return b() and return c() from within your then handlers.

then only "replaces" the first promise with a subsequent promise which is returned from its callback.

If your then callback doesn't return a promise, then the then applies to the original promise, and it will be executed immediately regardless of the contents/result of the previous then callback.

Basically...

a().then(function () {
  b()
}).then( # This "then" is chained off of a's promise

While conversely:

a().then(function () {
  return b()
}).then( # This "then" is chained off of b's promise

You need to return promises to chain them :

a().then(function (resultFromA) {
  console.log("a() responded with: " + resultFromA);
  // return b() promise
  return b();
}).then(function (resultFromB) { 
  console.log("b() responded with: " + resultFromB);
  // return c() promise
  return c();
}).then(function (resultFromC) { 
  console.log("c() responded with: " + resultFromC);
});

You forgot to return from function call. Javascript function does not return implicitly.

function a() { 
    return new Promise(function (resolve, reject) { 
        resolve("hi from a!");
    });
}

function b() { 
    return new Promise(function (resolve, reject) { 
        setTimeout(function () { 
            resolve("hi from b!");
        }, 5000);
    });
}

function c() { 
    return new Promise(function (resolve, reject) { 
        setTimeout(function () { 
            resolve("hi from c!");
        }, 1000);
    });
}

a().then(function (resultFromA) {
    console.log("a() responded with: " + resultFromA);
    return b(); // return 
}).then(function (resultFromB) { 
    console.log("b() responded with: " + resultFromB);
    return c(); // return
}).then(function (resultFromC) { 
    console.log("c() responded with: " + resultFromC);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!