I have a async function that awaits a promise which resolves when it receives some 'data'. However, when I run the test, I get a Error: Timeout of 300000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
Here is my code snippet, I am using this in truffle to test solidity contracts :
contract("Test", async (accounts) => {
it("test description", async () => {
let first = await getFirstEvent(oracle.LogResult({fromBlock:'latest'}));
let second = await getFirstEvent(oracle.LogResult({fromBlock:'latest'}));
Promise.all([first,second]);
//some assertion code
});
const getFirstEvent = (_event) => {
return new Promise((resolve, reject) => {
_event.once('data', resolve).once('error', reject)
});
}
});
Isn't the promise resolving ? I can see 'data' coming back in the callback because I am emitting the callback event in the solidity code I am testing.
I managed to resolve this issue, so posting it here so that others can use the approach.
I created a Promise that times out after a duration we can set :
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {a
reject(new Error('Request timed out'));
}, 200000);
})
Then, I race the timeoutPromise with the Promise which is fetching data, like this for the case I posted :
Promise.race([getFirstEvent(oracle.LogResult({fromBlock:'latest'})), timeoutPromise]);
It looks to me like there's a few things wrong here.
First of all, your function isn't returning anything i.e. it should be return Promise.all([first, second]);.
Secondly, if the goal of the promise.all is to execute the promises in parallel, then that's not what it's doing here because you already have await statements on those function calls above. What you are looking for here would be:
return await Promise.all([
getFirstEvent(oracle.LogResult({fromBlock:'latest'}),
getFirstEvent(oracle.LogResult({fromBlock:'latest'})]);
Now in terms of the promise not resolving, I'm assuming the event is generated from oracle.LogResult(). In this case, what you'd want to do is setup your promises to listen for the event first, for example:
let first = getFirstEvent();
let second = getSecondEvent();
Now you have 2 promises that are listening for the events. Next, you generate the event:
oracle.LogResult({ fromBlock: 'latest' });
oracle.LogResult({ fromBlock: 'latest' });
Finally, you ensure you wait on the result of the promises:
return await Promise.all([first, second]);
Related
I have a situation in my node.js program where I have an array of promises. I am prepared to wait a maximum of 200 ms for each promise in the array to get fulfilled, if it’s not fulfilled by then I want it to be rejected.
The code I have written for this works when I run my script in the terminal using node.js without a debugger attached.
However, when I debug the same script using VS code it stops as soon as a promise gets rejected due to timeout. The debugger claims that the rejection is an uncaught exception.
How can I change the code I have such that it does exactly what it does now, but a rejected promise doesn’t cause an exception?
I have tried adding try{} catch{} all over the place but cannot seem to find a solution.
Here is a minimal reproducible example of my issue (the debugger complains about the line reject( "timeout" ) ):
async function delayedPromise(delay) {
await new Promise((res) => setTimeout(res, delay));
return "success";
}
function rejectAfterDelay(ms) {
return new Promise((_, reject) => setTimeout(() => {
reject("timeout");
}, ms));
}
async function main() {
// Create array of promises.
promArr = [];
promArr.push(delayedPromise(100));
promArr.push(delayedPromise(200));
promArr.push(delayedPromise(300));
promArr.push(delayedPromise(400));
promArr.push(delayedPromise(500));
// Wait for all promises to either get fulfilled or get rejected after 200 ms.
const msMaxTime = 200;
const result = await Promise.allSettled(
promArr.map(promise => Promise.race([promise, rejectAfterDelay(msMaxTime)]))
);
console.log(result);
}
main()
Instead of racing a promise with a short-lived promise(rejectAfterDelay), we can wrap the promise in a short-lived promise:
async function delayedPromise(delay) {
return new Promise((res) => setTimeout(res, delay, 'success'));
}
// wrap the promise instead of racing it
function rejectAfterDelay(promise, ms) {
return new Promise((resolve, reject) => {
setTimeout(reject, ms, 'timeout');
// forward the reasons to the wrapper
promise.then(reason => resolve(reason))
.catch(err => reject(err));
});
}
async function main() {
// Create array of promises.
promArr = [];
promArr.push(delayedPromise(100));
promArr.push(delayedPromise(200));
promArr.push(delayedPromise(300));
promArr.push(delayedPromise(400));
promArr.push(delayedPromise(500));
// Wait for all promises to either get fulfilled or get rejected after 200 ms.
const msMaxTime = 200;
const result = await Promise.allSettled(
promArr.map(promise => {
//return Promise.race([promise, rejectAfterDelay(msMaxTime)]);
return rejectAfterDelay(promise, msMaxTime);
})
);
console.log(result.map(r => r.value ? r.value : r.reason));
}
main()
With this the debugger doesn't complain when Uncaught Exceptions option is selected.
Also, depending on your situation, instead of setTimeout(reject, ms, 'timeout') you can use setTimeout(resolve, ms, 'timeout') to make it fail gracefully.
I have the following observables
callOne() {
return new Observable(subscriber => {
subscriber.next(true);
setTimeout(() => {
subscriber.complete();
}, 3000)
})
}
callTwo() {
return new Observable(subscriber => {
subscriber.next(false);
setTimeout(() => {
subscriber.complete();
}, 1000)
})
}
so when i call subscribe to them
this.callOne().subscribe(data => {
console.log(data);
})
this.callTwo().subscribe(data => {
console.log(data);
})
i get immediately true and false printed, even that i setted complete method in the setTimeout.
With that i am saying that in x miliseconds there can't be emitted new values after the execution of the complete methhod.
When i try the same but this time the observables are converted into promises
let response1 = await this.callOne().toPromise();
console.log('response1', response1);
let response2 = await this.callTwo().toPromise();
console.log('response2', response2);
then i get printed true from the callOne observable in 3000 miliseconds.
Why is that ?
Why when i have promise the complete method is taken into consideration with the setTimeout
but with the observable it is not ?
you should change something in your code. You have to run next method in setTimout. because when you run next method observables triggered and also you subscribe an observable it will invoke.
callOne() {
return new Observable(subscriber => {
setTimeout(() => {
subscriber.next(true); // you can use like this
subscriber.complete();
}, 6000)
})
}
But when you use await it is working like then() and it will invoke when everything is done like complete.
I would imagine the promise does not resolve until the subscriber.complete() call. Since you used await, execution will not continue until the promise resolves.
This article actually explains that the promise returned from toPromise() waits for the observable to complete, then returns the last value: https://levelup.gitconnected.com/rxjs-operator-topromise-waits-for-your-observable-to-complete-e7a002f5dccb
toPromise() is deprecated though, so I wouldn't bother using it. You can just wrap Observables in Promises instead. Then you can control exactly when they resolve.
callOne() {
const observable = new Observable((subscriber) => {
subscriber.next(true);
setTimeout(() => {
subscriber.complete();
}, 3000);
});
return new Promise((resolve) => {
observable.subscribe((result) => resolve(result));
});
}
This promise will resolve on the first call of subscriber.next() which I believe is what you were expecting to happen.
Keep in mind Observables can call .next() repeatedly, but Promises can only resolve once.
Observables and promises are different things even though they might convert one into another.
What you are facing is expected. The promise does not "resolve" until the observable completes, so only after completion it run the logic, and that is how the promises work. Observable in that sense are different.
In fact, if you do not complete the stream, in the subscribe you still getting the code run, but in the promise as the stream never completes, it won't run anything. A very common mistake is to convert into promise from long-life hot observables.
I'm working on Ionic v4 with Angular.
In my project i use the BLE to communicate with a raspberry.
I have several step :
Search Device around me
Connect to this device
Activate Notification
Send Messages
Currently i have something like :
this.ble.scan().subscribe(result => {
if (device === theDeviceIWant) {
this.ble.connect(device.id).subscribe(result => {
this.ble.startNotification(infosaboutDevice).subscribe(result => {
// Message 1
this.ble.writeWithoutResponse(infos, message).then(result => {
// Message 2
this.ble.writeWithoutResponse(infos, message).then(result => {
// Message 3
this.ble.writeWithoutResponse(infos, message).then(result => {
// Message X
this.ble.writeWithoutResponse(infos, message).then(result => {
})
})
})
})
})
})
})
}
I want to do something like that :
this.myScan();
this.myConnect();
this.myNotification();
this.myMessage('Text 1');
this.myMessage('Text 2');
this.myMessage('Text X');
The probleme : My function ‘myConnect‘ don't wait the end of ‘myScan‘ to start. So somme stuff needed by ‘myConnect‘ is do in ‘myScan‘.
I already try to use ‘async/await‘ but does not work. I think i don't use it correctly :
await this.myConnect().then(async () => {
await this.myNotification().then(async () => {
await this.myMessage('03020000').then(async () => {
await this.myMessage('010100').then(async () => {
await this.myMessage('020200' + this.random.toString(16));
});
});
});
});
Help me to understand how to create a function who wait the end of the before one to start :D
Just use async/await OR then
await this.myConnect(); // this awaits the Promise returned by myConnect to be resolved
await this.myNotification(); // same for this Promise
await this.myMessage('03020000'); // and so on...
await this.myMessage('010100');
await this.myMessage('020200' + this.random.toString(16));
The keyword await makes JavaScript wait until that promise settles and
returns its result.
So you dont need to use then in await this.myConnect().then(()=>{});
use await this.myConnect();
Below is example which help you understand better
function SignalOne() {
return new Promise((resolve, reject) => {
setTimeout(()=>{
resolve('Hello iam signal one');
}, 2000);
});
}
function SignalTwo() {
return new Promise((resolve, reject) => {
setTimeout(()=>{
resolve('Hello iam signal Two');
}, 1000);
});
}
async function sendSignal() {
let one = await SignalOne();
let two = await SignalTwo();
console.log(one);
console.log(two);
}
sendSignal();
Try this:
async myScan() {
// do things
}
ngOnInit() {
const scan = this.myScan(); // myScan doesn't actually have to return here
await scan;
const connect = this.myConnect();
await connect;
// more stuff
}
This is essentially what Promises are made for.
A Promise is an object representing the eventual completion or failure
of an asynchronous operation.
You can read up about Promises here. Once you read thru that, I left an example for you below to demonstrate how to use a Promise:
//Wrap the operation you want to wait for in a Promise (in this case: setTimeout)
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('3 seconds have passed');
}, 3000);
});
//Once the operation is resolved the callback in the .then will be called
promise.then(val => document.querySelector('#target').innerHTML = val);
<div id="target">This message will change once the operation is resolved in 3 seconds.</div>
I would embrace Observables. Looking at what you want..
Search Device around me
Connect to this device
Activate Notification
Send Messages
1 and 2 would be chained with switchMap, as responses depend on each other. Then 3 and 4 could be performed in order, but not dependent on each other, therefore we could use concat with those. (If this is not correct flow, adjust accordingly with these two operators).
So I suggest the following:
import { never } from 'rxjs';
import { switchMap, concat } from 'rxjs/operators';
// ...
this.ble.scan().pipe(
switchMap((device) => {
if (device === theDeviceIWant) {
return this.ble.connect(device.id)
}
// terminates rest of code
return never();
}),
concat(
this.ble.startNotification(...),
this.ble.writeWithoutResponse(...)
)
).subscribe(data => console.log(data))
You're so close! Rather than using .then and async just use one or the other. Here are a few ways to accomplish what you are trying to do:
Using .then:
This is your typical chaining syntax. Promises can be chained using .then() and passing in a function. If the return value is a value (not a Promise) then it will resolve to that value. But if it did return a Promise then it will chain together and your next .then() will resolve to the "inner" async call result.
// Message 1
return this.ble.writeWithoutResponse(infos, message).then(result1 => {
// Message 2
return this.ble.writeWithoutResponse(infos, message);
}).then(result2 => {
// Message 3
return this.ble.writeWithoutResponse(infos, message);
)}.then(result3 => {
// Message X
return this.ble.writeWithoutResponse(infos, message);
}).then(result4 => { })
Using async/await
This approach achieves the same result but uses special keywords to automatically chain promises together. async/await allows you to skip the .then() and return calls so you can invoke your async functions as if they were synchronous.
// Message 1
let result1 = await this.ble.writeWithoutResponse(infos, message)
// Message 2
let result2 = await this.ble.writeWithoutResponse(infos, message);
// Message 3
let result3 = await this.ble.writeWithoutResponse(infos, message);
// Message X
let result4 = await this.ble.writeWithoutResponse(infos, message);
To learn more about Promise's and async javascript, check out these resources:
Promises on MDN
Promises on Google Web Fundamentals
Video on Async/Await
I have created a long running Promise that I'm wrapping with this simple function that I created to create a watch a Promise race.
The function is below:
export const promiseTimeout = (
promise,
timeoutMs = 10000, //10 secs
message = 'Timeout reached, please try again',
) =>
Promise.race([
promise,
new Promise((resolve, reject) =>
setTimeout(() => {
reject(message);
}, timeoutMs),
),
]);
The way I'm planning to use it is that I would pass the long running Promise that might require other unpredictable resources such as internet, file, system setting, etc.
Usage would be like below:
const result = await promiseTimeout(longRunningFunction())
.catch(err => /* do something with the error , show toast or alert */);;
What is currently happening with this is that whenever the timeout is reached it would call the catch but the operation of the longRunningFunction will still continue.
How can I stop the operations on the passed Promise in argument if ever timeout is reached?
How can I stop the operations on the passed Promise in argument if ever timeout is reached?
Hey, sorry, we don't have cancellation of async functions yet.
Note however that a promise is a value and not an action, once you have the promise given we won't have cancellable promises in JavaScript it is impossible to cancel the action.
The only thing you can do is to do something like the cancellation proposal and write your longRunningFunction with a token:
function longRunningFunction() {
const signal = { requested: false };
async function internal() {
// your regular code here
// whenever you can stop execution:
if(signal.requested) {
return; // and cancel internal operations
}
}
let res = internal();
res.signal = signal;
return res;
}
Then write your race as:
export const promiseTimeout = (
promise,
timeoutMs = 10000, //10 secs
message = 'Timeout reached, please try again',
) =>
Promise.race([
promise,
new Promise((resolve, reject) =>
setTimeout(() => {
reject(message);
if (promise.signal) promise.signal.requested = true;
}, timeoutMs),
),
]);
I'm trying to test a function which calls another module's function which returns a promise,
The problem is that jest does not wait for completion of the myFunction and jumps out of it and treat it as a promise, as result section shows the "done" message is printed before "resolve" message. I have work around using setImmediate but I rather not to use it and want to understand the reason.
the simplified version of the code is following:
The module which is mocked
// repo.js
const getItems = () => {
console.log('real');
return new Promise((resolve, reject) => {
setTimeout(
() => resolve('result'), 1000);
}
);
}
module.exports = {
getItems
};
Unit under test:
// sample.js
const repo = require('./repo');
const myFunction = (req, res) => {
console.log('myFunction');
repo.getItems()
.then(goals => {
console.log('resolve');
res.val = 'OK';
}).catch(err => {
console.log('reject');
res.val = 'Failed';
});
return;
};
module.exports = {myFunction};
Test file:
// sample.test.js
const repo = require('./repo');
const sample = require('./sample');
const result = {
'message': 'done'
};
describe('Tests for receiving items', () => {
it('should call and be successful. ', () => {
repo.getItems = jest.fn(() => {
console.log('mocking');
return new Promise((resolve) => ( resolve(result) ));
});
const response = {val: 'test'};
const request = {};
sample.myFunction(request, response);
console.log('done');
expect(response.val).toBe('OK');
})
}
);
The result is:
console.log MySample\sample.js:5
myFunction
console.log MySample\sampel.test.js:11
mocking
console.log MySample\sampel.test.js:17
done
console.log MySample\sample.js:9
resolve
Error: expect(received).toBe(expected)
Expected value to be (using ===):
"OK"
Received:
"test"
Expected :OK
Actual :test
The test you wrote reflects the correct usage, and you might say it fulfilled its purpose, because it uncovered a bug in your implementation.
To show what exactly went wrong, I will get rid of everything that is not needed, which leads to an even more minimal example. The following test file can be run by Jest and it reproduces your problem.
const myFunction = (res) => {
Promise.resolve()
.then(goals => {
res.val = 'OK';
}).catch(err => {
res.val = 'Failed';
});
return;
};
it('should call and be successful. ', () => {
const response = {val: 'test'};
myFunction(response);
expect(response.val).toBe('OK');
})
myFunction starts a promise (which resolves immediately here with no value) and returns nothing (undefined). You can also test the error part by using Promise.reject instead of Promise.resolve. When you call myFunction(response) the next line is executed when myFunction finishes. This is not when the promise actually finishes, but the function itself. The promise could take any amount of time and there is no way for you tell when it actually finished.
To be able to know when the promise finished, you need to return it, so you can use a .then() on it to execute something after the promise has been resolved. Both .then() and .catch() return a new promise which resolves with the returned value, which in this case is again undefined. That means you need to do your assertion in the .then() callback. Similarly, Jest thinks that the test ends as you exit the function even though it should wait for the promise to be settled. To achieve this you can return the promise from the test and Jest will wait for its completion.
const myFunction = (res) => {
// Return the promise from the function, so whoever calls myFunction can
// wait for the promise to finish.
return Promise.resolve()
.then(goals => {
res.val = 'OK';
}).catch(err => {
res.val = 'Failed';
});
};
it('should call and be successful. ', () => {
const response = {val: 'test'};
// Return the promise, so Jest waits for its completion.
return myFunction(response).then(() => {
expect(response.val).toBe('OK');
});
})
You can also use async/await, but keep in mind that you still need to understand how promises work, as it uses promises underneath. An async function always returns a promise, so Jest knows to wait for its completion.
it('async/await version', async () => {
const response = {val: 'test'};
// Wait for the promise to finish
await myFunction(response);
expect(response.val).toBe('OK');
})
Usually you would also return a value from the promise (in .then() or .catch()) instead of mutating an outer variable (res). Because if you use the same res for multiple promises, you will have a data race and the outcome depends on which promises finished first, unless you run them in sequence.