如何从承诺中获取价值

时间:2018-08-06 20:13:37

标签: javascript node.js

我一直在从事一个项目,对此我需要一些帮助: 我在函数内有一个promise,我需要返回“ current”的值,以便可以在其他地方使用它。 我正在从Firebase中检索数据,然后将结果洗牌并从结果中仅提取10个元素。

function retriveData() {

//declaration of variables ...

axios.get("Firebase link")
    .then((response) => {
        keyArray = Object.keys(response.data);
        let k = shuffle(keyArray); 
        //shuffle is a function to shuffle the key results
        for (var i = 0; i < 10; ++i) {
            current[i] = response.data[k[i]];
        }
    });
return current;} //I want this variable to end up with the promise result in current

我知道,这不是Promise的工作方式,但是我需要解决此问题的解决方案。 谢谢!

2 个答案:

答案 0 :(得分:0)

axios.get是异步的,因此您可以将回调传递给retrieveData,或者它本身需要返回Promise。没办法解决。

使用回调(无错误处理):

function retriveData(callback) {
  axios.get("Firebase link")
    .then((response) => {
      keyArray = Object.keys(response.data);
      let k = shuffle(keyArray); 
      //shuffle is a function to shuffle the key results
      for (var i = 0; i < 10; ++i) {
        current[i] = response.data[k[i]];
      }

      callback(null, current);
    });
}

retrieveData((err, result) => console.log(result));

使用承诺(无错误处理):

function retriveData() {
  return new Promise((resolve) => {
    axios.get("Firebase link")
      .then((response) => {
        keyArray = Object.keys(response.data);
        let k = shuffle(keyArray); 
        //shuffle is a function to shuffle the key results
        for (var i = 0; i < 10; ++i) {
          current[i] = response.data[k[i]];
        }

        resolve(current);
    });
}

retrieveData().then((result) => console.log(result));

[EDIT] 上面的示例是出于说明目的。由于axios.get已返回Promise,因此可以直接从retrieveData返回。

function retriveData() {
  return axios.get("Firebase link")
    .then((response) => {
      keyArray = Object.keys(response.data);
      let k = shuffle(keyArray); 
      //shuffle is a function to shuffle the key results
      for (var i = 0; i < 10; ++i) {
        current[i] = response.data[k[i]];
      }

      return current;
    });
}

retrieveData().then((result) => console.log(result));

答案 1 :(得分:0)

尝试一下:我将retriveData函数作为一个承诺,以便您可以在程序中的任何地方使用它

function retriveData() {

//declaration of variables ...
return new Promise((resolve, reject) => {

axios.get("Firebase link")
    .then((response) => {
        keyArray = Object.keys(response.data);
        let k = shuffle(keyArray); 
        //shuffle is a function to shuffle the key results
        for (var i = 0; i < 10; ++i) {
            current[i] = response.data[k[i]];
        }
       // if everything fine, if you get any conditional error then call reject();
       resolve(current);
    });
})
}


//call the function like promise
retriveData().then(result => {
//current will come here
     console.log('result comes here');
}).catch(error => {
    //error comes here (reject error)
   console.log('error');

})