如何将第一个诺言的返回价值传递给最后一个诺言



我有一个令人困惑的问题:

我正在使用承诺链来调用几个功能:

 CommonPromiseLists.checkStatusPromise().then(CommonPromiseLists.getChannelPreferencePromise).then(CommonPromiseLists.getChannelsPromise).then(getUniqueStory.bind(null, storyId))

您看到的功能被调用,因此我得到了正确的结果。但是,基于最近的要求更改,我需要将commonPromiseLists.checkstatuspromise((的返回值传递给getuniquestory.bind(null,storyid(,这是我所说的最后一个承诺。我有一个解决方案:因此,每当我返回并将返回的值交给下一个承诺时,我也可以包括第一个承诺的返回值。但是我相信应该有一种更简单的方法。有什么更好的方法可以获取checkstatuspromise((的返回值并将其传递给getuniquestory.bind(null,storyid,第一个承诺的返回值(?

您可以通过前景链传递结果,但这使得代码紧密耦合,要求成功的回调在解决值时预测一个奇怪的结构。

使用普通的承诺,一种更简单的方法是将其余的操作包装在checkStatusPromise回调中。这样,checkStatusPromise的结果就会暴露出来。

CommonPromiseLists.checkStatusPromise().then(res => {
  return CommonPromiseLists.getChannelPreferencePromise(res)
    .then(CommonPromiseLists.getChannelsPromise)
    .then(getUniqueStory.bind(null, storyId, res)) // access res
});

如果您可以使用async-wait,它会变得容易一些:

async enclosingFunction(){
  const status = await CommonPromiseLists.checkStatusPromise();
  const channelPreference = await CommonPromiseLists.getChannelPreferencePromise(status);
  const channels = await CommonPromiseLists.getChannelsPromise(channelPreference);
  const uniqueStory = await getUniqueStory.bind(null, storyId, res)
  return uniqueStory;
}
enclosingFunction().then(value => /* results */)

承诺可能不是您需要在这里使用的。看起来您需要发电机或异步/等待。我在这里使用异步/等待,因为它可能更容易理解。

想象您有一个函数返回这样的承诺

function double(someVal) {
    return new Promise(resolve => {
        setTimeout(() => {
          resolve(someVal * 2);
        }, 2000);
      });
}

您可以像这样的异步/等待

async function sumMultiplications() {
    var a = await double(5);
    var b = await double(20);
    var c = await double(a);
    return a + b + c;
}

调用异步功能时,它会返回承诺。当异步 功能返回值,承诺将通过 返回的值。当异步函数引发异常或一些 价值,承诺将被抛弃的价值拒绝。

https://developer.mozilla.org/en-us/docs/web/javascript/reference/refereny/statement/statement/ashync_function

如果需要的话,请保存结果:

let res;
func1().then(result=>{
    res = result;
    return func2();
})
.then(func3)
.then(func4)
...
then(result=>{
  ...
  return res; //return result that you save as result of the first promise
})
.catch(err=>{
  throw err;
})

如果您要省略一些步骤,您可以这样做:

let res;
func1().then(result=>{
    res = result;
    if(res) //you check of the result
       return func2().then(func3);
    else 
       return func4();
})
then(result=>{
  ...
  return res; //return result that you save as result of the first promise
})
.catch(err=>{
  throw err;
})

最新更新