簡體   English   中英

訪問諾言的價值。然后返回諾言之外的價值

[英]Access value that promise .then returns outside of promise

標題說明了一切,我正在使用async-library eachSeries方法

let 
  valueOne = null,
  validItem = null;

const asyncEachSeries = require('async/eachSeries');

const getContent = function (item) {
  contentResponse = fetchContent(item);
  return contentResponse;
}

if (recommendationsArr.length > 0) {
  asyncEachSeries(recommendationsArr, function (item, callback) {
    getApiContent(item).then(function getValidResult(response) {
      try { 
        valueOne = response.content.valueOne || null; //may or may not be present
        recommendationsArr.splice(recommendationsArr.indexOf(item), 1); 
        validItem = item;
        console.log("##### valueOne is: ", valueOne); // I get data here
        return true;
      } catch (err) {
        valueOne = null;
        return false;
      }
    });
    //I am guessing I need a return statement here, though not sure what
  });

  console.log("##### Outside promise, valueOne is: ", valueOne); // no data here

  // Access valueOne, validItem, recommendationsArr to be able to pass as props for the component 
  return {
    component: <Layout><ComponentName
      //pass other non-dependent props
      validItem={validItem}
      valueOne={valueOne}
      recommendationsArr={recommendationsArr}
    /></Layout>,
    title: `Page Title`,
  };
}

return null;

場景: recommendationsArr是一個項目數組(它的99.9%不為null,但是由於它是一個外部api調用,所以我希望進行檢查)。 其目的是讓值valueOnevalidItem ,和更新recommendationsArr
有效性取決於valueOne的存在,因此,如果valueOne recommendationsArr[0]具有有效的valueOne則無需為數組的其余部分獲取api結果。 我正在使用eachSeries因為它一次只運行一個異步操作,因此,如果該異步為我提供了有效的結果,那么我就不必遍歷其他項目。

推薦的recommendationsArr = ["blue", "white", "green", "red"]; //usually the array is anywhere between 12-50 elements樣本: recommendationsArr = ["blue", "white", "green", "red"]; //usually the array is anywhere between 12-50 elements樣本recommendationsArr = ["blue", "white", "green", "red"]; //usually the array is anywhere between 12-50 elements recommendationsArr = ["blue", "white", "green", "red"]; //usually the array is anywhere between 12-50 elements

現在,為了能夠將更新的值傳遞給組件,我需要能夠訪問asyncEachSeries迭代循環之外的try塊中設置的值。 我知道我將必須return已處理的/新值,但不確定何時以及如何返回這些值。

與有關異步代碼的任何問題一樣,通常使用callback函數返回值。 但是eachSeries不會收集返回值。 您想要的是async.mapSeries

async.mapSeries(recommendationsArr, function (item, callback) {
  getApiContent(item).then(function (response) {
    try { 
      valueOne = response.content.valueOne || null; //may or may not be present
      recommendationsArr.splice(recommendationsArr.indexOf(item), 1); 
      validItem = item;
      callback(null, valueOne); // This is how you return a value
      // return true; // return does absolutely nothing
    } catch (err) {
      valueOne = null;
      callback(err, valueOne);
      // return false;
    }
  });
},function (err, result) {
  // this is where you can process the result
  // note that the result is an array
});

但是,由於您使用的是Promise,因此可以使用async-q代替,它將caolan的異步庫包裝在Promise中:

var asyncQ = require('async-q');

asyncQ.mapSeries(recommendationsArr, function (item) {
  // Note: the return in the line below is important
  return getApiContent(item).then(function (response) {
    try { 
      valueOne = response.content.valueOne || null; //may or may not be present
      recommendationsArr.splice(recommendationsArr.indexOf(item), 1); 
      validItem = item;
      return valueOne; // this is how you return a value in a promise
    } catch (err) {
      return null
    }
  });
})
.then(function(result) {
  // you can process the result here
});

我個人更希望重寫代碼並在最后處理結果,因為代碼更簡潔:

asyncQ.mapSeries(recommendationsArr, getApiContent)
  .then(function (result) {
    for(var i=0;i<result.length;i++) {
      var response = result[i];
      // do what needs to be done with each response here
    }
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM