I have two promises compounded to abstract away all the bluetooth scanning logic in my mobile application written in Typescript, for Nativescript. I have the promise returned from a function I import into my HomeComponent. I want the then
in my HomeComponent to run only after all the logic in my scan routine is completed, at the moment, it runs as soon as the scan has started.
ble.scan.ts:
import * as dialogs from "ui/dialogs";
import * as bluetooth from "nativescript-bluetooth";
var devices: Array<bluetooth.Peripheral>;
var _peripheral: bluetooth.Peripheral;
export function scan() {
return bluetooth.hasCoarseLocationPermission().then(
(granted) => {
if (!granted) {
bluetooth.requestCoarseLocationPermission();
} else {
bluetooth.scan({
}).then(() => {
console.log("scanning complete");
if (this.devices == undefined) {
return null;
}
console.log("2"); // ************** SECOND ****************
}, (err) => {
console.log("error while scanning: " + err);
});
}
});
}
Home.Component.ts:
console.log("1"); // ************** FIRST ****************
this._ble.scan().then(
// Log the fulfillment value
function (val) {
console.log("3"); // ************** THIRD ****************
_this.addClicked = toggleAdd(_this.page, _this, _this.addClicked); //toggle button
_this.Connect(val);
})
How can I make these run in order?
Update:
In response to the duplicate comments, The linked answer seems to be about multiple then's executing after one another. My issue is about then's on different levels, e.g. I want the HomeComponent then
to execute after the ble.scan then
. In the linked answer, it is about multiple then's on the same level?
So I would like the 3 console.log's in my code to print out in order, i.e. 1,2,3 regardless of how long any of the calls etc. take. I am currently getting 1,3,2 - i.e. the third log is called as soon as te promise has been created, not when it has been resolved.
Update:
Taking the exact example from the linked question, I have:
test() {
addElement("first")
.then(
function (val){
addElement("second");
console.log("second.");
})
.then(
function (val){
addElement("third");
console.log("third.");
});
}
export function addElement(elementText){
return new Promise(function(resolve,reject){
setTimeout(function(){
console.log(elementText);
resolve();
}, Math.random() * 2000);
});
}
I would like these functions to print out, first, second., second, third., third
. However, I get:
JS: first JS: second. JS: third. JS: third JS: second
How do I get the then
to execute after the called promises' then has completed?