【问题标题】:Access to data from a previous Promise in a chain访问链中先前 Promise 的数据
【发布时间】:2019-07-09 15:12:38
【问题描述】:

我的问题是我想访问从以前的 then() 获取的数据,我该怎么做? (要求:我不能修改 externalBuiltInFunction() )

ajaxCall(...)
.then( (response) => {                          
    return response.json();
})
.then ( (jsonData) => {
    return externalBuiltInFunction(jsonData);
})
.then ((dataFromExternalFunction) => {
   ... here i want to use jsonData, how can i do ?...
}

感谢帮助

【问题讨论】:

  • 每个函数都采用前一个函数返回的内容,因此在前一个函数中返回jsonData,尽管可能有更好的方法来组织代码。

标签: javascript ecmascript-6 es6-promise


【解决方案1】:

您可以只使用一个then 语句和async/await

ajaxCall(...)
  .then(async response => {                          
    const jsonData = await response.json();
    const external = await externalBuiltInFunction(jsonData);
    // Here you still have access to jsonData and external 
  })

【讨论】:

  • 如果 async/await 不可用,Promise.all 也会起作用。
  • 非常感谢!
【解决方案2】:

您可以将jsonData 存储在外部词法环境中的变量中:

let jsonData;

ajaxCall(...)
    .then( (response) => {
        return response.json();
    })
    .then ( (jsonData) => {
        jsonData = jsonData;
        return externalBuiltInFunction(jsonData);
    })
    .then ((dataFromExternalFunction) => {
        // jsonData is available here
    }

或者,您可以将jsonData 作为数组显式传递给下一个.then,结果为externalBuiltInFunction 调用:

ajaxCall(...)
    .then( (response) => {
        return response.json();
    })
    .then ( (jsonData) => {
        return Promise.all([externalBuiltInFunction(jsonData), jsonData]);
    })
    .then (([dataFromExternalFunction, jsonData]) => {
        // jsonData is available here
    }

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2018-09-17
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2023-04-04
    • 2019-04-25
    • 1970-01-01
    相关资源
    最近更新 更多