Javascript中的执行顺序?

时间:2016-09-09 11:59:42

标签: javascript node.js ecmascript-6 wit.ai

我试图在控制台上显示来自api的一些数据,但似乎我不明白代码执行在ES6中是如何工作的。

getMovieReccomendation({context, entities}){
    return new Promise(function (resolve, reject) {
        var movie = firstEntityValue(entities, 'movie')
        if ('movie') {
            var movieData = omdbapicall(movie);
            console.log(movieData);
            context.movieReccomendation = 'You should see ' + movieData.Title;
            delete context.missingMovieTitle;
        } else {
            context.missingMovieTitle = true;
            delete context.movieReccomendation;
        }
        return resolve(context);
    })
}

};

function omdbapicall(movieTitle) {
console.log(movieTitle);
request('http://www.omdbapi.com/?t=' + movieTitle + '&plot=short&r=json', function (error, response, body) {
    if (error) {
        throw error;
    }
    if (response.statusCode == 200) {
        var apiData = JSON.parse(body);
        var movieInfo = {
            "Title": apiData.Title,
            "Plot": apiData.Plot,
            "imdbRating": apiData.imdbRating,
            "imdbVotes": apiData.imdbVotes
    };
    console.log(apiData);
    return apiData;
    }
})

}

我得到的错误如下:

Memento
undefined
TypeError: Cannot read property 'Title' of undefined
at C:\Users\Derp\WebstormProjects\moviereccomendation\examples\quickstart.js:69:76
at Object.getMovieReccomendation (C:\Users\Derp\WebstormProjects\moviereccomendation\examples\quickstart.js:64:16)
at C:\Users\Derp\WebstormProjects\moviereccomendation\lib\wit.js:121:36
at process._tickCallback (internal/process/next_tick.js:103:7)
JSON Object returned by API

所以我认为错误是由执行顺序引起的,因为代码试图在我的getMoveReccomendation函数中继续执行我的omdbapicall。

我想我只需要等待函数完成,因为它在错误后记录了JSON对象,但我不知道如何。

0 个答案:

没有答案