Javascript:写入返回promise的函数

时间:2017-12-02 13:18:52

标签: javascript google-cloud-functions

我正在尝试在Firebase函数中创建一个返回promise的函数(或同步返回,我不介意),但没有成功。

这是我写的函数:

function doSomethingLong(param) {
    https.get('http://www.myurl.com?param=' + param, (resp) => {
        let data = '';

        // A chunk of data has been recieved.
        resp.on('data', (chunk) => {
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("Call succeeded. Response: " + data);
            return true;
        });
    }).on("error", (err) => {
        console.log("Call failed. Error: " + err.message);
        return false;
    });
}

我希望在Firebase发生某些更改时调用它,并等到它完成,例如:

exports.someFunction = functions.database.ref('/users/{user_id}/param').onCreate(event => {
    const param = event.data.val();

    if (doSomethingLong(param)) {
        console.log("ttt");
    } else {
        console.log("fff");
    }
    return null;
})

无论我尝试什么,someFunction函数都会在doSomethingLong结束之前结束。

任何线索?

3 个答案:

答案 0 :(得分:2)

您必须创建一个Promise并在异步任务结束时解决/拒绝它。

OUTPUT:

[0.7 0.6 0.6 0.4 0.3 0.3]

现在你可以像这样使用它了

function doSomethingLong(param) {

   return new Promise(function(resolve, reject){

       https.get('http://www.myurl.com?param=' + param, (resp) => {
          let data = '';

          // A chunk of data has been recieved.
          resp.on('data', (chunk) => {
              data += chunk;
          });

          // The whole response has been received. Print out the result.
          resp.on('end', () => {
              console.log("Call succeeded. Response: " + data);
              resolve();
          });
      }).on("error", (err) => {
          console.log("Call failed. Error: " + err.message);
          reject(err);
      });
   });
}

答案 1 :(得分:0)

做类似的事情,

    function doSomethingLong(param) {
    return new Promise(function(resolve,reject){
        https.get('http://www.myurl.com?param=' + param, (resp) => {
            let data = '';

            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            });

            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                console.log("Call succeeded. Response: " + data);
                resolve(data);//resolve data
            });
        }).on("error", (err) => {
            console.log("Call failed. Error: " + err.message);
            reject(err);//reject(reason)
        });
    });
}


exports.someFunction = functions.database.ref('/users/{user_id}/param').onCreate(event => {
    const param = event.data.val();

    if (addUserToNewsletter(user_id, name, email, language)) {
        console.log("ttt");
    } else {
        console.log("fff");
    }
    return null;
    let promise=doSomethingLong('foo');
    promise.then((data)=>{
        console.log(data);
    }).catch((err)=>{
        console.log(err);
    })
})

答案 2 :(得分:0)

你可以通过返回promise,promise.resolve或promise.reject来加入他们。

让您的代码看起来像这样:

 this.props.doSomethingLong(loginResult.credential)
          .then(result => this.someFunction(result))
          .catch(error => this.handleError(error.message))

这样做:

exports.someFunction = functions.database.ref('/users/{user_id}/param').onCreate(event => {
const param = event.data.val();

if (addUserToNewsletter(user_id, name, email, language)) {
    console.log("ttt");
} else {
    console.log("fff");
}
return Promise.resolve();

})

执行此每个函数调用,您可以在Node-js

中阅读有关Promise及其工作方式的更多信息