Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将已解析承诺的内容存储在变量中_Javascript_Node.js - Fatal编程技术网

Javascript 如何将已解析承诺的内容存储在变量中

Javascript 如何将已解析承诺的内容存储在变量中,javascript,node.js,Javascript,Node.js,我有一个包含承诺的函数。函数执行HTTP请求,我希望解析它并将响应作为变量中的值返回 function sendCommand(auth, playerId, command) { return new Promise((resolve, reject) => { request.post(`https://test.com/${playerId}/command`,{ headers: { Authorization: auth },

我有一个包含承诺的函数。函数执行HTTP请求,我希望解析它并将响应作为变量中的值返回

function sendCommand(auth, playerId, command) {
    return new Promise((resolve, reject) => {
        request.post(`https://test.com/${playerId}/command`,{
            headers: { Authorization: auth },
            json: {
                "arg": `${command}`
            }
        }, function status(err, response, body) {
            if (response.statusCode === 200) {
                resolve(body)
            } else {
                reject(err)
            }
          }
        )  
    })
}
我从其他文件运行此函数,因此执行以下操作:

module.exports = {
    doSomething: (playerId, command) => {
        loginHelper.getToken().then(token =>
        sendCommand(token, playerId, command))
    }
}
在另一个文件中,我希望将解析的响应存储在如下变量中:

const commandHelper = require(__helpers + 'command-helper')

let test = commandHelper.doSomething(playerId, 'command')

我希望测试变量包含响应数据。

您应该在异步函数中使用wait 例如:

function hi(){
  return new Promise((res,rej)=>{
       res("hi");
   }
}
async function see(){
   var hiStr = await hi();
   console.log(hiStr); // hi
}

你没有。你必须在整个过程中保持异步。承诺是“病毒性的”,没有办法取消它们,所以一旦你开始使用它们(而且你经常不得不开始使用它们),你就要继续使用它们。从
doSomething
返回承诺。然后
执行其他操作。当我运行此代码时,console.log打印
未定义的
。这是正确的吗?