通过承诺链传递变量

时间:2018-01-09 17:11:10

标签: javascript rest api es6-promise

我对承诺略显新意,所以请原谅我缺乏知识。下面的代码突出显示了我想要做的事情,但显然我无法做到。

<TwitterKit/TWTRKit.h>

我需要运行每个函数并传入&#34; token&#34;和&#34; id&#34;。通过这样做,每个函数上面的方式同时运行。我需要它们在彼此之后执行,但是传递所需的变量。

基本上我需要登录,创建一个&#34;集合&#34;,删除&#34;集合&#34;。这是我设置的一些测试的一部分。

2 个答案:

答案 0 :(得分:1)

这是一个可读且同步的替代方法,可以使用async/await使用Promise(实际上它仍然使用Promise)

// returns a Promise whose response is the token
const requestAccessToken = cmsUrl => request(/* request options with cmsUrl */)

// returns a Promise whose response is the collectionId
const createCollection = token => request(/* request options with token */)

// returns a Promise whose response is given by deleting the respective collection
const deleteCollection = collectionId => request(/* request options with collectionId */)

// create and execute an async function that puts all these functions together in a synchronous manner
const createThenDeleteCollection = async cmsUrl => {
  try { // if at any time an error is thrown, the error is caught and logged
    const token = await requestAccessToken(cmsUrl)
    const collectionId = await createCollection(token)
    const responseFromDeletingCollection = await deleteCollection(collectionId)
    console.log(responseFromDeletingCollection)
  } catch (err) {
    console.error(err)
  }
}
createThenDeleteCollection(process.env.CMS_URL)

使用此方法的一个警告是,如果您在浏览器中执行它,IE不支持它,如果您在Node中执行,则至少需要使用7.6版< / p>

答案 1 :(得分:0)

这里有一个简单的例子,说明如何通过promise链传递值。

const one = () => new Promise((resolve) => {
    return resolve(1)
});

const two = (val) => new Promise((resolve) => {
    return resolve(val * 5);
})

const three = (val, val2) => new Promise((resolve) => {
    return resolve(val + val2);
}) 

one().then((r) => {
    //r is 1
    console.log('r is 1:', r)
  return r
})
//we pass the return value from the previous to the two function
.then(two)
.then((r) => {
    //r is 1 * 5
  console.log('r is 1 * 5:', r)
  return three(r, 10)
})
.then((r) => {
  //r is now 5 + 10
    console.log('r is now 5 + 10:', r)
})

如果需要传递多个值,请使用数组或对象。 https://jsfiddle.net/rfk2Lxku/