如何从提取节点函数返回字符串

时间:2018-12-18 19:38:13

标签: javascript json themoviedb-api

我正在使用电影数据库API,并尝试在youtube上播放预告片,因为我需要JSON响应中的键值。我尝试了一切,但该函数返回了promise或未定义。我试图使用回调函数返回结果,但是那也不起作用。

const fetch = require('node-fetch');
// function declaration 
async function trailer(id, callback) {
  var video = 'https://api.themoviedb.org/3/movie/' + id + '/videos?api_key=' + apiKey +'&language=en-US';
  var key = await fetch(video)
    .then(res => res.json())
    .then(json => callback(json.results[0].key));
}

// function call returns a promise (expected key string ex."Zftx5a")
trailer(id, function(result){return result;})

1 个答案:

答案 0 :(得分:0)

由于fetch函数进行异步调用,因此您的trailer函数在承诺链解析之前将返回key。解决该问题的最简单方法是使用async函数,因此您的代码将类似于:

async function trailer(id) {
  var video = 'https://api.themoviedb.org/3/movie/' + id + '/videos?api_key=' + apiKey +'&language=en-US';
  return await fetch(video)
    .then(res => res.json())
    .then(json => json.results[0].key);  
}

但是,您必须考虑到async函数将返回promise,因此您将必须修改代码。

有关更多信息,请检查以下链接:

https://www.npmjs.com/package/node-fetch#common-usage

https://developers.google.com/web/fundamentals/primers/promises

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function