Promise function returns undefined - javascript

Help, I'm just trying to learn the promise function. I am confused how to return the promise function value.
static getTrailer(movieId) {
return fetch(`http://api.themoviedb.org/3/movie/${movieId}?api_key=###&append_to_response=videos`)
.then(response => {
return response.json();
})
.then(responseJson => {
if (responseJson.videos.results[0]) {
Promise.resolve(responseJson.videos.results[0].key)
.then(result => {
console.log(result);
return result;
});
} else {
return Promise.reject(`Trailer is not found`);
}
});
}
This is where i tried to get the result
<p>${DataSource.getTrailer(this._movie.id).then(resultKey => {console.log("data is: " + resultKey)})}</p>
But the resultKey always return undefined value. How can i fix this ?

if (responseJson.videos.results[0]) { then you don't return anything, so the promise resolves as undefined.
And why are you even doing anything with Promise.resolve in the first place?
Get rid of the pointless extra promise, and return the value you want to resolve the then with.
.then(responseJson => {
if (responseJson.videos.results[0]) {
const result = responseJson.videos.results[0];
console.log(result);
return result;
} else {
return Promise.reject(`Trailer is not found`);
}
});

To pass data down a promise chain, you need to return (either explicitly, or implicitly from an arrow function)
Here it is, nice and simple;
static getTrailer(movieId) {
return fetch(`http://api.themoviedb.org/3/movie/${movieId}?api_key=###&append_to_response=videos`)
.then(response => response.json())
.then(responseJson => responseJson.videos.results[0].key) // an error thrown for whatever reason, will caught below.
.catch(error => {
// an error thrown by any of the three preceding stages will end up here
throw new Error(`Trailer is not found`); // throwing is less expensive than returning Promise.reject()
});
}

You don't need to use promise for the get the key again.
static getTrailer(movieId) {
return fetch(`http://api.themoviedb.org/3/movie/${movieId}?api_key=###&append_to_response=videos`)
.then(response => {
return response.json();
})
.then(responseJson => {
if (responseJson.videos.results[0]) {
result = responseJson.videos.results[0].key;
console.log(result);
return result;
} else {
return Promise.reject(`Trailer is not found`);
}
});
}

Related

nodejs express Why not return res?

I want to finish if isBookmark is true
Enter the then below and console.log(1); This works, I hope it doesn't work
checkLecture(addLectureInformation)
.then(() => {
return insertLecture(addLectureInformation);
})
.then((succesInsertLecture) => {
if (true) {
return res.status(200).json(succesInsertLecture);
} else {
return Promise.all([1]);
}
})
.then(num => {
console.log(1);
})
Help
You can't skip steps in your promise chain, but you can move the last then so it is not called if you returned a response already:
checkLecture(addLectureInformation)
.then(() => {
return insertLecture(addLectureInformation);
})
.then((succesInsertLecture) => {
// this should be other condition, because this will be true always and "else" is not even needed/run
if (true) {
return res.status(200).json(succesInsertLecture);
} else {
// Moving the last "then" here, so it is not called is you have sent a response already
return Promise.all([Promise.resolve(1)]) // Promise all expects an array of promises
.then(num => {
console.log(1);
})
}
});

How to use Promise.all with if statement init

For last few hours I am trying to make condition inside Promise.all to read images if there is a path for it or to pass a specific value if there is not.
When I use my code results that I get in next .then part is undefined. I checked the values that I am passing, they are not undefined. What can cause the problem?
Here is my code:
readPostImages: (rows) => {
return Promise.all(
rows.map((value) => {
if (value.firstImage != "null") {
return fs.promises.readFile(value.firstImage, {
encoding: "base64",
});
} else {
return Promise.resolve("null");
}
})
);
},
And here is my App.js that return undefined:
.then((result) => {
postModules.readPostImages(result);
})
.then((result) => {
console.log(result);
// return postModules.addImagesToData(rows, result);
})

Rejecting Promise if many error sources

Im in situation where I have many potential error sources. Is there an elegant solution to this mess?
How should I reject it?
function myFuction(hash) {
return new Promise((resolve, reject) => {
// this could return error
const id = atob(hash);
// this could return error
let data = firstFunction(id);
// return error if not true
if (data && data.id) {
// this could return error
return secondFunction(data.id)
.then(item => {
// return error if not true
if (item) {
// this could return error
return thirdFunction(item)
.then(payload => {
resolve('OK');
});
}
});
}
});
}
Avoid the Promise constructor antipattern! You can use early returns with Promise.reject or just throw errors:
function myFuction(hash) {
return Promise.resolve().then(() => {
// this could throw error
const id = atob(hash);
// this could throw error
let data = firstFunction(id);
// return error if not true
if (!data || !data.id)
return Promise.reject(new Error("…")); // alternative: throw new Error("…");
return secondFunction(data.id);
}).then(item => {
// return error if not true
if (!item)
return Promise.reject(new Error("…")); // same here
return thirdFunction(item);
}).then(payload => 'OK');
}
(Additionally I applied some flattening, but as long as your always return from promise callbacks you could nest as well)

Understanding of the promises chaining: 'then()' get's undefined parameter as the result

I started to work deeply with promises, and need your help to understand why this code doesn't work as expected.
Here is what I need:
After successful profile retrieving the code should log out ('success getting Profile!') which it does, and return true as result, that should be passed to the next then() element. But instead of true, I get undefined as the result.
public verifyAuth(): angular.IPromise<boolean> {
let promise: ng.IPromise<boolean> = this._Token.getIdToken()
.then((idToken) => {
if (!idToken) {
return false;
}
else if (this._Profile.isEmpty()) {
promise = this.retrieveProfileInfo()
.then(() => {
this._$log.log('success getting Profile!');
return true;
});
} else {
return true;
}
})
.catch((error) => {
this._Token.clearToken();
this._$log.error(error);
return false;
});
return promise;
}
You are returning the first promise object before your reassign it later in the success then block. You don't need to do it just use chaining like this:
public verifyAuth(): angular.IPromise<boolean> {
let promise: ng.IPromise<boolean> = this._Token.getIdToken()
.then((idToken) => {
if (!idToken) {
return false;
}
else if (this._Profile.isEmpty()) {
return this.retrieveProfileInfo()
.then(() => {
this._$log.log('success getting Profile!');
return true;
});
} else {
return true;
}
})
.catch((error) => {
this._Token.clearToken();
this._$log.error(error);
return false;
});
return promise;
}
Note, how you simply return this.retrieveProfileInfo() which becomes new promise automatically.

Extracting functions in a Promise chain

I am wanting to refactor a Promise chain by extracting out some functions. Currently I have
const getData = (uuid) => {
return new Promise((resolve) => {
fetch(
// go fetch stuff
)
.then((response) => {
if (!response.ok) {
return resolve(false);
}
return response;
})
.then(fetchres.json)
.then(response => {
// Do more stuff that requires resolves that I will also want to refactor
})
.catch(err => {
console.log(err);
resolve(false);
});
});
};
So I want to extract the part where I resolve the unsuccessful responses. But pass along any successful ones. I have pulled it out like so.
const resolveUnsuccessfulResponses = (response) => {
if (!response.ok) {
return response.resolve(false);
}
return response;
}
const getData = (uuid) => {
return new Promise((resolve) => {
fetch(
// go fetch stuff
)
.then(resolveUnsuccessfulResponses)
.then(fetchres.json)
.then(response => {
// Do more stuff that requires resolves that I will also want to refactor
})
.catch(err => {
console.log(err);
resolve(false);
});
});
};
Now I'm understandably getting the error resolve is not defined. How can I resolve this Promise in an external function?
Should I pass resolve to my extracted function? That would seem clunky.
.then(response => resolveUnsuccessfulResponses(response, resolve))
I might end up having something like
.then(fetchres.json)
.then(parseResponseData)
.then(postDataSomewhere)
.then(doOtherThings)
.then(doEvenMoreCoolThings)
And to have to pass response and resolve to each of them seems wrong
You should return a new Promise from your external functions aswell:
const resolveUnsuccessfulResponses = (response) => {
return new Promise((resolve, reject) => {
if (!response.ok) {
return resolve(false);
}
return resolve(response);
});
}

Categories

Resources