Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

javascript - Issue with promises

I am trying to use promises. Basically puting http connections in one js and calling from another js. But I am not able to do so. What's the mistake here?

http.js

'use strict';
const fetch = require('node-fetch');

module.exports.get = async (url) => {
  console.log("inside get method");
  const promise = new Promise(function (resolve, reject) {
    console.log("inside promise");
    fetch(url)
      .then(res => {
        console.log("inside fetch");
        resolve(res.json());
      })
      .catch(json => reject(Error(json)));
  })
  return promise;
}

 

main.js

'use strict';
const http = require('/opt/http.js')

module.exports.httpTest = async (event) => {
  let url = 'http://www.someurl.com/';
  console.log("calling get method");
  http.get(url).then(
  function (data) {
  console.log("inside http then")
  console.log(data);
}).catch(function (data) {
  console.log(data);
});
console.log("exited get method");
}

As you can see in http.js I have written a wrapper for GET request which I am trying to use in main.js.

When I execute main.js, nothing fails, but not get displayed on console. What I am doing wrong here?

UPDATE

I have added console logs everywhere... and when I call httpTest from anywhere, here is what I am getting

calling get method
inside get method
inside promise
exited get method

basically it's not going inside fetch

question from:https://stackoverflow.com/questions/65948076/issue-with-promises

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don’t create a useless extra promise.

  // this is a code smell
  const promise = new Promise(function (resolve, reject) {
    console.log("inside promise");
    fetch(url)
      .then(res => {
        console.log("inside fetch");
        resolve(res.json());
      })
      .catch(json => reject(Error(json)));
  })
  return promise;

Just return fetch(url); which already returns a promise. Your wrapper promise adds nothing.

Second, your exited get method is going to run outside the promise chain. If you want that to run after get finishes you need to await the http.get call inside HttpTest.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...